import { Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { IAccount } from '../interface/account.interface';
import { IAccountForCity } from '../interface/account_city.interface';

@Injectable()
export class AccountService {

  constructor(@InjectModel('Account') private readonly AccountModule: Model<IAccount>) {}

  // 创建用户
  async createAccount(account: IAccount) {
    await this.AccountModule.create(account);
  }

  // 获取所有账户信息
  async getAccount(limit): Promise<IAccount[]> {
    return await this.AccountModule.find().sort( { id: -1 } ).limit( limit );
  }

  // 通过 id 获取账户信息
  async getAccountById(id): Promise<IAccount> {
    return await this.AccountModule.findOne( { id } );
  }

  // 通过账户名获取账户信息
  async getAccountByName(name): Promise<IAccount> {
    return await this.AccountModule.findOne( { account_name: name } );
  }

  // 获取账户数
  async getAccountCount(): Promise<number> {
    return await this.AccountModule.count();
  }

  // 更新头像
  async updateAvatar(id, avatar) {
    await this.AccountModule.findOneAndUpdate( { id }, { $set: { avatar } } );
  }

  // 获取用户城市分布
  async getAccountForCity(): Promise<IAccountForCity> {
    const cities = ['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉'];
    let accountForCity: IAccountForCity = null;
    const filters = Object.keys(accountForCity);
    for (let [ index, city ] of cities.entries()) {
      accountForCity[ filters[ index ] ] = this.AccountModule.find( { create_city: city } ).count();
    }
    accountForCity.qita = this.AccountModule.$where( `!cities.includes(this.create_city)` ).count();
    return accountForCity;
  }

}